package com.neu.ui;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.neu.po.Book;
import com.neu.po.User;
import com.neu.service.BookService;
import com.neu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/book")
public class BookController {
    @Autowired
    BookService bookService;

    @Autowired
    UserService userService;
    @GetMapping("/findAllByUserId/{userId}")
    public String findAllByUserId(@PathVariable("userId")Integer userId,Model model){
        return "index";
    }
    @GetMapping("/list")
    public String findAllBycurUserId(@RequestParam(value="page",defaultValue="1")int page,HttpSession session, Model model, String userId){
        User cur_user = (User) session.getAttribute("user");
        Integer uId = null;
        if (cur_user == null){
            uId = Integer.parseInt(userId);
            User user = userService.findById(uId);
            session.setAttribute("user",user);
        }else{
            uId = cur_user.getId();
        }
        /* 用户没写好，用1号用户测试*/
        PageHelper.startPage(page,5,"book_time");
        List<Book> books = bookService.findAllByUserId(uId);
        PageInfo<Book> pageInfo = new PageInfo<>(books);
        model.addAttribute("books",pageInfo);
        return "booklist";
    }

    @GetMapping("/cancelBook/{bookId}")
    public String cancelBook(@PathVariable("bookId")Integer bookId){
        bookService.cancelBookBybookId(bookId);
        return "redirect:/book/list";
    }

}
